﻿//文件夹根据模块化创建一对一
//只有仓储才能访问领域模型
using Jst.Core;
using Jst.Core.Utility;
using Jst.Domain;
using Jst.IRepository;
using Jst.Common;
using SqlSugar;
namespace Jst.Repository
{
    public class AuthRepository : IAuthRepository
    {
        private readonly DbManager _dbManager;

        public AuthRepository(DbManager dbManager)
        {
            _dbManager = dbManager;
        }

        private ISqlSugarClient DbBaseClient => _dbManager.DefaultDb;

        /// <summary>
        /// 获取用户账号
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<SysUserInfo> GetAccount(string account, string password)
        {
            return await DbBaseClient.Queryable<SysUserInfo>().FirstAsync(_ => _.LoginName == account && _.LoginPWD == password && _.IsDeleted == false);
        }

        /// <summary>
        /// 获取用户角色权限
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<string> GetUserRoleNameStr(string account, string password)
        {
            string roleName = "";
            var user = await DbBaseClient.Queryable<SysUserInfo>().Where(_ => _.LoginName == account && _.LoginPWD == password && _.IsDeleted == false).FirstAsync();
            var roleList = await DbBaseClient.Queryable<Role>().Where(_ => _.IsDeleted == false).ToListAsync();
            var userRoles = await DbBaseClient.Queryable<UserRole>().Where(_ => _.UserId == user.Id).ToListAsync();
            if (userRoles.Count > 0)
            {
                var arr = userRoles.Select(ur => ur.RoleId.ObjectToString()).ToList();
                var roles = roleList.Where(d => arr.Contains(d.Id.ObjectToString()));
                roleName = string.Join(',', roles.Select(r => r.Name).ToArray());
            }
            return roleName;

        }

        /// <summary>
        /// 根据Id获取用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<SysUserInfo> GetUserInfoByIdAsync(long Id)
        {
            return await DbBaseClient.Queryable<SysUserInfo>().Where(_ => _.Id == Id && _.IsDeleted == false).FirstAsync();
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<object> GetRoleListAsync(long Id)
        {
            var query = await DbBaseClient.Queryable<Role>()
                       .LeftJoin<UserRole>((a, b) => a.Id == b.RoleId)
                       .LeftJoin<SysUserInfo>((a, b, c) => b.UserId == c.Id)
                       .Where((a, b, c) => c.IsDeleted == false && a.Enabled == true)
                       .GroupBy((a, b, c) => new { a.Id, a.Description, a.Name })
                       .Select((a, b, c) => new
                       {
                           AppID = a.Id.ToString(),
                           RoleCode = a.Description,
                           RoleName = a.Name,
                           RoleType = ""
                       }).ToListAsync();

            return query;
        }

        /// <summary>
        /// 获取路由树
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<object> GetLoginMenue(long Id)
        {
            // 获取用户角色ID
            var roleIds = await DbBaseClient.Queryable<UserRole>()
                        .Where(_ => _.IsDeleted == false && _.UserId == Id)
                        .Select(_ => _.RoleId)
                        .Distinct()
                        .ToListAsync();

            if (!roleIds.Any())
                return null;

            // 获取角色权限ID
            var pids = await DbBaseClient.Queryable<RoleModulePermission>()
                      .Where(_ => _.IsDeleted == false && roleIds.Contains(_.RoleId))
                      .Select(_ => _.PermissionId)
                      .Distinct()
                      .ToListAsync();

            if (!pids.Any())
                return null;

            // 获取角色权限模块
            var rolePermissionModules = await DbBaseClient.Queryable<Permission>()
                                        .Where(_ => pids.Contains(_.Id) && _.IsButton == false)
                                        .OrderBy(c => c.OrderSort).ToListAsync();

            // 递归构建权限树的方法
            List<dynamic> BuildPermissionTree(List<Permission> permissions, long parentId)
            {
                return permissions
                    .Where(item => item.Pid == parentId)
                    .OrderBy(item => item.OrderSort)
                    .Select(item => new
                    {
                        id = item.Id,
                        name = item.Name,
                        pid = item.Pid,
                        order = item.OrderSort,
                        path = item.Code,
                        iconCls = item.Icon,
                        Func = item.Func,
                        IsHide = item.IsHide.ObjectToBool(),
                        IsButton = item.IsButton.ObjectToBool(),
                        meta = new
                        {
                            requireAuth = true,
                            title = item.Name,
                            NoTabPage = item.IsHide.ObjectToBool(),
                            keepAlive = item.IskeepAlive.ObjectToBool()
                        },
                        children = BuildPermissionTree(permissions, item.Id) // 使用 item.Id
                    })
                    .Cast<dynamic>() // 将匿名对象转换为 dynamic
                    .ToList();
            }

            // 构建权限树
            return BuildPermissionTree(rolePermissionModules, 0);
        }

        /// <summary>
        /// 获取角色权限Id
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<List<long>> GetUserRoleIds(long Id)
        => await DbBaseClient.Queryable<UserRole>().Where(_ => _.UserId == Id).Select(_ => _.RoleId).Distinct().ToListAsync();




    }
}
